################################################################################
# Project	name : examinator-proj
# Description	 : Python Google WebApp
# Purpose	     : Examination Web-program
# Date	       : 2011
# Contributers	: Steven, Jan, Google & The Web  
################################################################################

import cgi
import os
import datetime
import logging

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from examination_util import get_given_answer
from examination_util import examination_score
from examination_util import correct_answer
from examination_util import is_in_time

################################################################################
# Data model objects
################################################################################  

class Question(db.Model):
  question = db.StringProperty(multiline=True)
  alternatives = db.StringListProperty()
  correct = db.IntegerProperty(required=True)
  correct_answer = correct_answer
    
class Student(db.Model):
  googleUser = db.UserProperty()       # google account
  fullName = db.StringProperty()       # no nickname, optional 
  
class Exam(db.Model):
  name = db.StringProperty()           # Name of exam
  duration = db.IntegerProperty()      # in minutes
  questions = db.ListProperty(db.Key)  # Questions List
  weights = db.ListProperty(int)       # weight of question

class Examination(db.Model):
  exam = db.ReferenceProperty(Exam)
  examinee = db.UserProperty()
  answers = db.ListProperty(int)
  start_time = db.DateTimeProperty()
  stop_time = db.DateTimeProperty()
  score = db.FloatProperty()

class Tutor(db.Model):               # Can make exams and grants others to do so
  googleUser = db.UserProperty()      
  isGranted = db.BooleanProperty()   # Tutor has rights to make Exams
  granted_by = db.SelfReferenceProperty()    # Who, which user gave grant privilige
  grant_date = db.DateTimeProperty()  # Date when grant privilege is set
  grant_privilige = db.BooleanProperty() # user who may grant permission
  
################################################################################
# Helpers functions Application
################################################################################

def is_current_user_tutor():
  if users.is_current_user_admin():
    return True
  user = users.get_current_user()
  query = db.GqlQuery("SELECT * FROM Tutor WHERE googleUser = :1 ", user)
  matching_tutors = query.fetch(1)
  if len(matching_tutors) == 0:
    return False
  matching_tutor = matching_tutors[0]
  if matching_tutor.isGranted:
    return True
  else:
    return False

def is_current_user_aspirant():
  user = users.get_current_user()
  query = db.GqlQuery("SELECT * FROM Tutor WHERE googleUser = :1 ", user)
  matching_tutors = query.fetch(1)
  if len(matching_tutors) == 0:
    return False
  matching_tutor = matching_tutors[0]
  if matching_tutor.isGranted:
    return False
  else:
    return True
    

def is_current_user_granter():
  if users.is_current_user_admin(): ## God-Like
    return True
  user = users.get_current_user()
  query = db.GqlQuery("SELECT * FROM Tutor WHERE googleUser = :1 ", user)
  matching_tutors = query.fetch(1)
  if len(matching_tutors) == 0:
    return False
  matching_tutor = matching_tutors[0]
  return matching_tutor.grant_privilige

  
# Belows is decorator declaration and functionality
# Only Tutors may browse, create and edit questions, exams.
def tutors_only(fn):
    def guarded_get(self):
      if (is_current_user_tutor() == False):
        self.redirect('/');
        return;
      else:
        return fn(self)
    return guarded_get

# decorator to get user which is Tutor with grant_privilege
# Athough till now once used it's needed in order to filter
# before the get() method of webAppRequestHandler
def tutors_with_grant_privilege_only(fn):
  def guarded_get(self):
    if (is_current_user_granter() == False):
      self.redirect('/');
      return;
    else:
      return fn(self)
  return guarded_get         


def get_current_user_tutorId():
  user = users.get_current_user()
  userId = -1
  query = db.GqlQuery("SELECT * FROM Tutor WHERE googleUser = :1 ", user)
  matching_tutors = query.fetch(1)
  if len(matching_tutors) == 0:
    return userId;
  matching_tutor = matching_tutors[0]
  return matching_tutor.key().id();


def get_current_user_tutor():
  user = users.get_current_user()
  userId = -1
  query = db.GqlQuery("SELECT * FROM Tutor WHERE googleUser = :1 ", user)
  matching_tutors = query.fetch(1)
  if len(matching_tutors) == 0:
    return userId;
  matching_tutor = matching_tutors[0]
  return matching_tutor;


# Put whatever admin in Tutor table at startup of WebApp
def make_admin_tutor():
  if not users.is_current_user_admin():
    return;
  user = users.get_current_user()
  query = db.GqlQuery("SELECT * FROM Tutor WHERE googleUser = :1 ", user)
  matching_tutors = query.fetch(1)
  if len(matching_tutors) > 0: # already in table
    return;
  tutor = Tutor();
  tutor.googleUser = user;
  tutor.isGranted  = True;
  tutor.grant_date = datetime.datetime.now();
  tutor.grant_privilige = True;
  tutor.put();
  tutor.granted_by = tutor;
  tutor.put();
  
################################################################################
# Entry-point Application
################################################################################

class MainPage (webapp.RequestHandler):
  def get(self):
    user_current = ''
    if users.get_current_user():
      url = users.create_logout_url(self.request.uri)
      url_linktext = 'Logout'
      user_current = users.get_current_user().email()
    else:
      url = users.create_login_url(self.request.uri)
      url_linktext = 'Login'

    template_values = {
       'url':url,
       'url_linktext': url_linktext,
       'user_current': user_current
    }

    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, template_values))

    make_admin_tutor(); # function ensure each admin has all the rights


################################################################################
# classes and function manipulating the Question entity
################################################################################

class QuestionsBrowsePage(webapp.RequestHandler):
  def get(self):
    # only Tutors may browse and edit questions
    if (is_current_user_tutor() == False):
      self.redirect('/');
      return;
    query = Question.all()
    question_list = query.fetch(20)
    for q in question_list:
      q.id = q.key().id()
      #q.isReferenced = referenceCheck(q)   # used tro see if question was related to an Exam

    template_values = {
      'questions': question_list
    }

    path = os.path.join(os.path.dirname(__file__), 'questions_browse.html')
    self.response.out.write(template.render(path, template_values))

##def referenceCheck(question):
##  query = db.GqlQuery("SELECT * FROM Exam WHERE questions = :1", question.key())
##  matching_questions = query.fetch(1)
##  if len(matching_questions) > 0:
##    return True
##  else:
##    return False
  

class QuestionSubmitPage(webapp.RequestHandler):
  def post(self):
    # only Tutors may add or edit questions
    if (is_current_user_tutor() == False):
      self.redirect('/');
      return;
    my_id = self.request.get('id')
    question_string = self.request.get('question')
    alt0 = self.request.get('alt0')
    alt1 = self.request.get('alt1')
    alt2 = self.request.get('alt2')
    alt3 = self.request.get('alt3')
    correct = int(self.request.get('correct'))
    if (my_id == 'new'):
      q = Question(correct=correct)
    else:
      q = Question.get_by_id(int(my_id))
      q.correct = int(correct)
      
    q.question = question_string
    alternatives = [alt0, alt1, alt2, alt3]
    q.alternatives = alternatives
    q.put()
    # self.redirect('/question_edit?id=' + str(q.key().id()))
    self.redirect('/questions_browse');


class QuestionJSON(webapp.RequestHandler):
  def get(self):
    term = self.request.get('term')
    logging.info("term: " + term);
    query = db.GqlQuery("SELECT * FROM Question WHERE question >= :1 AND question < :2", term, term + u"\ufffd")
    matching_questions = query.fetch(10)
    logging.info("matching: " + str(matching_questions));
    json = '['
    json_list = map(lambda x: '{"label":"' + x.question + '","id":' + str(x.key().id()) + '}' , matching_questions)
    json += ', '.join(json_list)  
    
    json += ']'
    logging.info("json: " + json);
    self.response.headers['Content-Type'] = "application/json"
    self.response.out.write(json)

    
class QuestionEditPage(webapp.RequestHandler):
  @tutors_only # only Tutors may browse and edit questions
  def get(self):
    my_id = self.request.get('id')
       
    if (my_id == 'new'):
      question = Question(correct=0)
      question.alternatives = ['', '', '', '']
    else:
      question = Question.get_by_id(int(my_id))  # wrong here if param ?id=xxxx or id=new is passed to edit-form
    
    template_values = {
      'id'      : my_id,
      'question': question.question,
      'alt0'    : question.alternatives[0],
      'alt1'    : question.alternatives[1],
      'alt2'    : question.alternatives[2],
      'alt3'    : question.alternatives[3],
      'correct' : question.correct
    }
    
    path = os.path.join(os.path.dirname(__file__), 'question_edit.html')
    self.response.out.write(template.render(path, template_values))

##class QuestionDelete(webapp.RequestHandler):
##   def get(self):
##     question_id = self.request.get('questionId')
##     question = Question.get_by_id(int(question_id))
##     question_key = question.key();
##     question.delete();
##     # Also remove reference to the question in Exams object.
##     # SELECT FROM Exam WHERE Exam.questions == question_key;
##     self.redirect('/questions_browse');


class JSONPage(webapp.RequestHandler):
  def get(self):
    examId = self.request.get('examId')
    #logging.info('examId: ' + examId)
    exam = Exam.get_by_id(int(examId))
    examName = exam.name
    question_key_list = exam.questions
    json = '{"qList": '
    question_list = []
    for q in question_key_list:
        question_list.append(Question.get(q))
    json += '['
    json_list = map(toJSON, question_list)
    json += ', '.join(json_list)  
    json += ']'
  # json += ', "header": "pipo", "duration": ' + str(exam.duration) + ' }'
    json += ', "header": "' + examName + '", "duration": ' + str(exam.duration) + ' }'
    self.response.headers['Content-Type'] = "application/json"
    self.response.out.write(json)

def toJSON(question):
  result = ''
  query = question.question
  alt0 = question.alternatives[0]
  alt1 = question.alternatives[1]
  alt2 = question.alternatives[2]
  alt3 = question.alternatives[3]
  # correct= question.correct (hide correct answers from examinee)
  result = '{"question": "' + query + '", "alternatives": ['
  result += '"' + alt0 + '",'
  result += '"' + alt1 + '",'
  result += '"' + alt2 + '",'
  # result += '"' + alt3 + '"], "correct": ' + str(correct) + "}"
  result += '"' + alt3 + '"]' + "}"
  return result


################################################################################
# classes manipulating the Exam object
################################################################################  

class ExamsBrowsePage(webapp.RequestHandler):
  @tutors_only # only Tutors may browse and edit exams
  def get(self):
    query = Exam.all()
    exam_list = query.fetch(24)
    for e in exam_list:
      e.id = e.key().id()

    template_values = {
      'exams': exam_list
    }

    path = os.path.join(os.path.dirname(__file__), 'exams_browse.html')
    self.response.out.write(template.render(path, template_values))


class ExamAddNewExam(webapp.RequestHandler):
  @tutors_only  # only Tutors may add new exams
  def get (self):
    template_values = []
    path = os.path.join(os.path.dirname(__file__), 'exam_new.html')
    self.response.out.write(template.render(path, template_values))
    
  def post(self):
    exam_name = self.request.get('ExamName')
    exam_duration = int(self.request.get('myDuration'))
       
    ex = Exam(name=exam_name)
    ex.name = exam_name
    ex.duration = exam_duration
    ex.questions = []
    ex.weights = []

    ex.put()
    ## TODO: remove logging info later
    logging.info("Exam added: "+ ex.name);

    examNew_Id = ex.key().id()
    self.redirect('/exam_edit?id=' + str(examNew_Id))
    path = os.path.join(os.path.dirname(__file__), 'exam_edit.html')

class ExamEditPage(webapp.RequestHandler):
  @tutors_only # only Tutors may edit new exams  
  def get(self):
    my_id = self.request.get('id')
    exam = Exam.get_by_id(int(my_id)) 

    questionList = loadQuestions(exam.questions)    
    template_values = {
      'id'       : my_id,
      'name'     : exam.name,
      'duration' : exam.duration,
      'questions': questionList
    }
    
    path = os.path.join(os.path.dirname(__file__), 'exam_edit.html')
    self.response.out.write(template.render(path, template_values))


def loadQuestions(questionKeys):
  result = []
  for questionKey in questionKeys:
    question = Question.get(questionKey)
    if not(question == None):
      questionId = question.key().id()
      question.id = questionId
      result.append(question)
    else:
      continue
  return result


class ExamSubmitPage(webapp.RequestHandler):
  def post(self):
    examId = self.request.get('examId')
    exam = Exam.get_by_id(int(examId))
    examName = self.request.get('examName')
    examDuration = self.request.get('examDuration')

    exam.name = examName
    exam.duration = int(examDuration)
    # questions are saved in ExamAddQuestion and ExamDeleteQuestion
    exam.put();104002
    logging.info("Exam submitted: "+ ex.name);
    self.redirect('/')
     



class ExamAddQuestion(webapp.RequestHandler): # add a question to the question list related to an Exam
  @tutors_only # only Tutors may browse and edit exams
  def get(self):
    exam_id = self.request.get('examId')
    append = self.request.get('append')
    question_id_to_be_added = self.request.get('questionId')
    exam = Exam.get_by_id(int(exam_id))
    keyToBeAdded = (Question.get_by_id(int(question_id_to_be_added))).key()
        
    if (append):
      exam.questions.append(keyToBeAdded)  
    else:     
      beforeQuestionId = self.request.get('beforeQuestionId')
      beforeQuestion = Question.get_by_id(int(beforeQuestionId))
      positionKey = beforeQuestion.key()
      index = exam.questions.index(positionKey)
      exam.questions.insert(index, keyToBeAdded)

    exam.put()     

    self.redirect('/exam_edit?id=' + exam_id)


class ExamDeleteQuestion(webapp.RequestHandler): # delete a question from the question list related to an Exam
  def get(self):
    exam_id = self.request.get('examId')
    question_id = self.request.get('qId')
    exam = Exam.get_by_id(int(exam_id))
    question_to_be_removed = Question.get_by_id(int(question_id))
    question_key_to_be_removed = question_to_be_removed.key()
    exam.questions.remove(question_key_to_be_removed)
    exam.put()
    self.redirect('/exam_edit?id=' + exam_id)


class ExamDelete(webapp.RequestHandler):
   def get(self):
     exam_id = self.request.get('examId')
     exam = Exam.get_by_id(int(exam_id))
     exam_key = exam.key();
     exam.delete();
     self.redirect('/exams_browse');

# Used for Exam look-up
class ExamJSON(webapp.RequestHandler):
  def get(self):
    term = self.request.get('term')
#   logging.info("term: " + term);
    query = db.GqlQuery("SELECT * FROM Exam WHERE name >= :1 AND name < :2", term, term + u"\ufffd")
    matching_exams = query.fetch(10)
    logging.info("matching: " + str(matching_exams));
    json = '['
    json_list = map(lambda x: '{"label":"' + x.name + '","id":' + str(x.key().id()) + '}' , matching_exams)
    json += ', '.join(json_list)  
    
    json += ']'
    logging.info("json: " + json);
    self.response.headers['Content-Type'] = "application/json"
    self.response.out.write(json)



################################################################################
# classes manipulating the Student object
################################################################################  

class StudentsBrowsePage(webapp.RequestHandler):
    @tutors_only # only Tutors may browse and edit exams  
    def get(self):
      query = Student.all()
      student_list = query.fetch(20)
      for s in student_list:
        s.id = s.key().id()

        template_values = {
        'students': student_list
         }
      path = os.path.join(os.path.dirname(__file__), 'students_browse.html')
      self.response.out.write(template.render(path, template_values))


class StudentEditPage(webapp.RequestHandler):
  @tutors_only # only Tutors may browse and edit exams  
  def get(self):
    my_id = self.request.get('id')
       
    if (my_id == 'new'):
      student = Student(name="")
      student.email = ""
    else:
      student = Student.get_by_id(int(my_id))
    
    template_values = {
      'id'      : my_id,
      'name'    : student.name,
      'email'   : student.email
    }
    path = os.path.join(os.path.dirname(__file__), 'student_edit.html')
    self.response.out.write(template.render(path, template_values))


class StudentSubmitPage(webapp.RequestHandler):
  def post(self):
    my_id = self.request.get('id')
    student_name = self.request.get('name')
    student_email = self.request.get('email')
    if (my_id == 'new'):
      s = Student(name=student_name)
    else:
      s = Student.get_by_id(int(my_id))

    s.name = student_name
    s.email = student_email
    s.put()
    # self.redirect('/student_edit?id='+str(s.key().id()))
    self.redirect('/student_edit?id=new')

class StudentGoogleLogIn(webapp.RequestHandler):
  def get(self) :
    user_current = ''
    if users.get_current_user():
      url = users.create_logout_url(self.request.uri)
      url_linktext = 'Logout'
      user_current = users.get_current_user().email()
    else:
      url = users.create_login_url(self.request.uri)
      url_linktext = 'Login'
        
    template_values = {
       'url':url,
       'url_linktext': url_linktext,
       'user_current': user_current
    }
    path = os.path.join(os.path.dirname(__file__), 'student_google_login.html')
    self.response.out.write(template.render(path, template_values))


class StudentPickExam(webapp.RequestHandler):
  def get(self):
    query = Exam.all()
    exam_list = query.fetch(30)
    # Filter, exclude exams on empty questions
    non_empty_exams = filter(lambda x: x.questions != [], exam_list)
    def addKey(x):
      x.id = x.key().id()
      return x
    exam_final_list = map(addKey, non_empty_exams)
    # logging.info("Final list: " + str(exam_final_list))
    template_values = {
      'exams': exam_final_list
    }
    path = os.path.join(os.path.dirname(__file__), 'student_exam_pick.html')
    self.response.out.write(template.render(path, template_values))
      
                         
class StudentStartExamination(webapp.RequestHandler):
  def get(self):
    examId = self.request.get('examId')
# logging.info("StudentStartExamination -examId: " + str(examId));
    exam = Exam.get_by_id(int(examId))
    examKey = exam.key();
    examination = Examination();
    examination.exam = examKey;
    examination.examinee = users.get_current_user();
    examination.start_time = datetime.datetime.now();
    examination.put();
    examinationKey = examination.key();
    # Other info as exam name are send through JSON    
    self.redirect('/static/LinuxExam.html?examId=' + examId + '&examinationId=' + str(examinationKey.id()))

class StudentStopExamination(webapp.RequestHandler):
  def post(self):
    MIN_SCORE = 6.0   # store in db Eaxm as global setting  ???
    examId = self.request.get('examId')
    # logging.info("StudentStopExamination -examId: " + str(examId));
    exam = Exam.get_by_id(int(examId));
    exam_lenghth = len(exam.questions)
    given_answers = []
    for n in range(0, exam_lenghth):
      given_answers.append(self.request.get('gruppe' + str(n)))

    # logging.info("Given answers: " + str(given_answers));
    correct_answers = []
    for qKey in exam.questions:
      q = Question.get(qKey)
      correct_answers.append(q.correct_answer())
    # logging.info("Given: " + str(given_answers) + "Correct: " + str(correct_answers))
    examination = Examination.get_by_id(int(self.request.get('examinationId')))
    examination.stop_time = datetime.datetime.now()
    # calc score of the two created lists
    score_ = examination_score(correct_answers, given_answers) 
    examination.score = round(score_, 2);
    examination.put();
     
    # redirect to a html (print) page with results on success
    # on condition that score >= MIN_SCORE and
    # start_time - stop_time <= duration
    if (examination.score >= MIN_SCORE):
        if (is_in_time(examination.start_time, examination.stop_time, exam.duration) == True):
          logging.info("Start-Stop: " + str(examination.stop_time - examination.start_time));
          examinationId = int(self.request.get('examinationId'))
          self.redirect('examination_result?examinationId=' + str(examinationId));
        else:
          examination.score = 0;
          examination.put();
    else:    
        self.redirect('/');


class StudentExaminationResult(webapp.RequestHandler):
  @tutors_only # only Tutors may browse and edit exams  
  def get(self):
    examination = Examination.get_by_id(int(self.request.get('examinationId')))
    examName = examination.exam.name
    examinationScore = examination.score
    examinee = examination.examinee
    #examDate    = str(examination.stop_time.year()) + ", " + str(examination.stop_time.date.month()) + ", " + str(examination.stop_time.date.day())
    examDate = examination.stop_time.strftime("%d,%m,%Y")
    
    template_values = {
      'examName'  : examName,
      'examScore' : examinationScore,
      'examinee'  : examinee,
      'examDate'  : examDate
    }
    path = os.path.join(os.path.dirname(__file__), 'student_exam_result.html')
    self.response.out.write(template.render(path, template_values))
    
    
################################################################################
# TODO: classes manipulating the Examination object
################################################################################  
  
class ExaminationsBrowsePage(webapp.RequestHandler):
  @tutors_only   # closure functionality call
  def get(self):
    query = Examination.all()
    examination_list = query.fetch(30)
    for exList in examination_list:
      exList.id = exList.key().id()
      exam = exList.exam
      exList.examName = exam.name

    template_values = {
    'examinations': examination_list
    }

    path = os.path.join(os.path.dirname(__file__), 'examinations_browse.html')
    self.response.out.write(template.render(path, template_values))

class ExaminationCreate(webapp.RequestHandler):
  @tutors_only # only Tutors may browse and edit examinations
  def post(self):
    exam_id = self.request.get('examId')
    student_id = self.request.get('studentId')
    examAdd = Exam.get_by_id(int(exam_id))
    student = Student.get_by_id(int(student_id))

    examination = Examination(exam=examAdd)
    examination.examinee = student
    examination.put()
    self.redirect('/')

################################################################################
# classes manipulating the Tutor object
################################################################################  
       
class TutorRegistration(webapp.RequestHandler):    # initial Tutor registration
  def post(self):
    # If user is already in database then do nothing in this phase
    # Optionally an un-subscribe by the user should be implemented 
    if (is_current_user_tutor() == True): # Already registered earlier 
         # Let user notify for un-subscribe
        self.redirect('/tutor_panel'); 
        return; 
    # Put logged in (google) user in Tutor db with no rights    
    tutor = Tutor();
    tutor.googleUser = users.get_current_user();
    tutor.isGranted = False;
    tutor.grant_privilige = False;
    tutor.put();
            

# This needs thinking over (remove completely or set flag of isGranted etc.
class TutorUnRegistration(webapp.RequestHandler):    # initial Tutor registration
  def post(self):
    # If user is already in database then do nothing in this phase
    # Optionally an un-subscribe by the user should be implemented 
    if (is_current_user_tutor() == False): # Already registered earlier 
        return; 
    # Find Tutor and delete entry in Tutor table    
    userId = get_current_user_tutorId();
    tutor = Tutor.get_by_id(int(userId));
    # tutor_to_be_removed = Tutor.get_by_id(int(userId))
    # tutor_key_to_be_removed = tutor_to_be_removed.key()
    tutor.remove(userId);
    tutor.put();
    

class TutorsBrowsePage(webapp.RequestHandler):
  @tutors_with_grant_privilege_only
  def get(self):
    # Only Tutors with grant_privilige may browse other Tutors
##    if is_current_user_granter() == False:
##        return;
    #logging.info("tutors_browse LOG!!!");
    query = Tutor.all()
    tutor_list = query.fetch(30)
    
    # Filter, exclude tutors which already are granted
    non_granted_tutors = filter(lambda x: x.isGranted == False, tutor_list)
    def addKey(x):
      x.id = x.key().id()
      email = x.googleUser.email()
      x.userMail = email;
      if x.granted_by:
        x.granted_by_name = x.granted_by.googleUser.email()
      else:
        x.granted_by_name = 'Not yet'
        
      return x
    
    tutor_final_list = map(addKey, non_granted_tutors)

    template_values = {
      'tutors': tutor_final_list
    }
    
    path = os.path.join(os.path.dirname(__file__), 'tutors_browse.html')
    self.response.out.write(template.render(path, template_values))
            

class TutorEditPage(webapp.RequestHandler):
  def get(self):
    # Only Tutors with grant_privilige may edit other Tutors
    if is_current_user_granter() == False:
        return;
    my_id = self.request.get('id')
    tutor = Tutor.get_by_id(int(my_id)) 

    if tutor.granted_by:
      granted_by_name = tutor.granted_by.googleUser.email()
    else:
      granted_by_name = 'Not yet'

    if tutor.grant_date:
      grantDate = tutor.grant_date
    else:
      grantDate = 'No date'
      
    template_values = {
      'id'              : my_id,
      'Tutor'           : tutor.googleUser.email(),
      'isGranted'       : tutor.isGranted,
      'grantDate'       : tutor.grant_date,
      'grantedBy'       : granted_by_name,
      'grantPrivilige'  : tutor.grant_privilige
    }
    path = os.path.join(os.path.dirname(__file__), 'tutor_edit.html')
    self.response.out.write(template.render(path, template_values))
      

class TutorSubmitPage(webapp.RequestHandler):
  def post(self):
    # Only Tutors with grant_privilige may edit other Tutors
    if is_current_user_granter() == False:
        self.error(403)
        return;
    my_id = self.request.get('id')
#   print "Tutor edit id: " , my_id 
    tutor = Tutor.get_by_id(int(my_id))
    # only set grant_date on datetime.now() when isGranted is currently False
    # else leave current date
    if tutor.isGranted == False: # prev state of isGranted is False 
        if bool(self.request.get('isGranted')) == True:
            tutor.isGranted = True;
            tutor.grant_date = datetime.datetime.now();
#    else:                        # prev state of isGranted is True 

    tutor.grant_privilige = bool(self.request.get('grantPrivilige'));
    tutor.granted_by = get_current_user_tutor() # for which boolean field ??
    
    tutor.put();
    self.redirect('/tutors_browse')


application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                      ('/questions_browse', QuestionsBrowsePage),
                                      ('/question_add', ExamAddQuestion),
                                      ('/question_search_json', QuestionJSON),
                                      ('/question_edit', QuestionEditPage),
                                      ('/question_submit', QuestionSubmitPage),
                                      ('/json', JSONPage),
                                      ('/exams_browse', ExamsBrowsePage),
                                      ('/exam_new', ExamAddNewExam),
                                      ('/exam_edit', ExamEditPage),
                                      ('/exam_submit', ExamSubmitPage),
                                      ('/exam_search_json', ExamJSON),
                                      ('/delete_from_exam', ExamDeleteQuestion),
                                      ('/student_google_login', StudentGoogleLogIn),
                                      ('/students_browse', StudentsBrowsePage),
                                      ('/student_edit', StudentEditPage),
                                      ('/student_submit', StudentSubmitPage),
                                      ('/examinations_browse', ExaminationsBrowsePage),
                                      ('/examination_create', ExaminationCreate),
                                      ('/student_exam_pick', StudentPickExam),
                                      ('/examination_start', StudentStartExamination),
                                      ('/examination_stop', StudentStopExamination),
                                      ('/examination_result', StudentExaminationResult),
                                      ('/tutor_registration', TutorRegistration),
                                      ('/tutor_unregistration', TutorUnRegistration),
                                      ('/tutors_browse', TutorsBrowsePage),
                                      ('/tutor_edit', TutorEditPage),
                                      ('/tutor_submit', TutorSubmitPage)
                                      ],
				       debug=True)


def main():
  run_wsgi_app(application)
  
if __name__ == "__main__":
  main()

